package oris.main;

import dialogos.OrisDialogoConfirmacao;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JOptionPane;
import oris.components.EnumDirecoes;
import oris.components.MoveThread;
import oris.components.OrisBorder;
import oris.components.OrisEvent;
import oris.components.ResizeThread;
import oris.paginas.pgPlayer;

public class Master extends javax.swing.JFrame implements MouseMotionListener {
    // <editor-fold defaultstate="collapsed" desc="Construtores">
    
    /** Creates new form Master */
    public Master() {
        initComponents();

        setLocationRelativeTo(null); 
        this.addMouseMotionListener(this);
        pnlConteudo.addMouseMotionListener(this);
        
        inicializarTitulo();
        inicializarFerramentas();
        inicializarConteudo();
    }
    
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Codigo Gerado">
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlBarraDeTitulo = new javax.swing.JPanel();
        btnFechar = new botao.OrisButton();
        btnRestaurarMaximizar = new botao.OrisButton();
        btnMinimizar = new botao.OrisButton();
        pnlBarraDeFerramentas = new javax.swing.JPanel();
        orisButton4 = new botao.OrisButton();
        pnlConteudo = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setUndecorated(true);

        pnlBarraDeTitulo.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        btnFechar.setText("orisButton1");
        btnFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFecharActionPerformed(evt);
            }
        });

        btnRestaurarMaximizar.setText("orisButton2");
        btnRestaurarMaximizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRestaurarMaximizarActionPerformed(evt);
            }
        });

        btnMinimizar.setText("orisButton3");
        btnMinimizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMinimizarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlBarraDeTituloLayout = new javax.swing.GroupLayout(pnlBarraDeTitulo);
        pnlBarraDeTitulo.setLayout(pnlBarraDeTituloLayout);
        pnlBarraDeTituloLayout.setHorizontalGroup(
            pnlBarraDeTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlBarraDeTituloLayout.createSequentialGroup()
                .addContainerGap(861, Short.MAX_VALUE)
                .addComponent(btnMinimizar, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnRestaurarMaximizar, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnFechar, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        pnlBarraDeTituloLayout.setVerticalGroup(
            pnlBarraDeTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlBarraDeTituloLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlBarraDeTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnFechar, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
                    .addComponent(btnRestaurarMaximizar, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
                    .addComponent(btnMinimizar, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE))
                .addContainerGap())
        );

        pnlBarraDeFerramentas.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        orisButton4.setText("orisButton4");
        orisButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                orisButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlBarraDeFerramentasLayout = new javax.swing.GroupLayout(pnlBarraDeFerramentas);
        pnlBarraDeFerramentas.setLayout(pnlBarraDeFerramentasLayout);
        pnlBarraDeFerramentasLayout.setHorizontalGroup(
            pnlBarraDeFerramentasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBarraDeFerramentasLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(orisButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(927, Short.MAX_VALUE))
        );
        pnlBarraDeFerramentasLayout.setVerticalGroup(
            pnlBarraDeFerramentasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBarraDeFerramentasLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(orisButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pnlConteudo.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        javax.swing.GroupLayout pnlConteudoLayout = new javax.swing.GroupLayout(pnlConteudo);
        pnlConteudo.setLayout(pnlConteudoLayout);
        pnlConteudoLayout.setHorizontalGroup(
            pnlConteudoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 1013, Short.MAX_VALUE)
        );
        pnlConteudoLayout.setVerticalGroup(
            pnlConteudoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 545, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pnlConteudo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pnlBarraDeFerramentas, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pnlBarraDeTitulo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlBarraDeTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlBarraDeFerramentas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlConteudo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Eventos">
    
    private void orisButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_orisButton4ActionPerformed
        inserirNovaPagina(_componentes[0]);
    }//GEN-LAST:event_orisButton4ActionPerformed

    private void btnFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFecharActionPerformed
        int option = OrisDialogoConfirmacao.showConfirmDialog(this, "Deseja realmente sair?", "Sair", JOptionPane.OK_CANCEL_OPTION);
        
        switch(option){
            case JOptionPane.OK_OPTION:
                System.exit(0);
                break;
            default:
        }
    }//GEN-LAST:event_btnFecharActionPerformed

    private void btnRestaurarMaximizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRestaurarMaximizarActionPerformed
        if(getExtendedState() == NORMAL){
            setExtendedState(MAXIMIZED_BOTH);
        }else if(getExtendedState() == MAXIMIZED_BOTH){
            setExtendedState(NORMAL);
        }
    }//GEN-LAST:event_btnRestaurarMaximizarActionPerformed

    private void btnMinimizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMinimizarActionPerformed
        setExtendedState(ICONIFIED);
    }//GEN-LAST:event_btnMinimizarActionPerformed
    
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Main e Variaveis Principais">
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Master().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private botao.OrisButton btnFechar;
    private botao.OrisButton btnMinimizar;
    private botao.OrisButton btnRestaurarMaximizar;
    private botao.OrisButton orisButton4;
    private javax.swing.JPanel pnlBarraDeFerramentas;
    private javax.swing.JPanel pnlBarraDeTitulo;
    private javax.swing.JPanel pnlConteudo;
    // End of variables declaration//GEN-END:variables
    
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Métodos Privados">
    
    private void inicializarTitulo() {
        
    }
    
    private void inicializarFerramentas() {
        
    }
    
    private void inicializarConteudo() {
        _componentes = new Component[1];
        
        _componentes[0] = new pgPlayer();        
        
        for (Component component : _componentes) {
            component.setSize(1000, 500);
        }
        
        inserirNovaPagina(_componentes[0]);
    }
    
    private void inserirNovaPagina(Component comp){
        pnlConteudo.removeAll();
        
        pnlConteudo.add(comp);
        pnlConteudo.repaint();
        pnlConteudo.revalidate();
    }
    
    /**
     * Baseado na posição do mouse, computa qual o cursor adequado para o momento.
     * @param e O evento do mouse
     */
    private void organizaDirecoes(MouseEvent e) {
        if(borda.isOnBorder(getSize(), e.getX(), e.getY()) && e.getComponent().getClass().getName().equals("oris.main.Master")){
            direcao = borda.isInWhichEdge(this.getSize(), e.getX(), e.getY());

            switch(direcao){
                case NORTE:
                    setCursor(new Cursor(Cursor.N_RESIZE_CURSOR));
                    break;
                case NORDESTE:
                    setCursor(new Cursor(Cursor.NE_RESIZE_CURSOR));
                    break;
                case LESTE:
                    setCursor(new Cursor(Cursor.E_RESIZE_CURSOR));
                    break;
                case SUDESTE:
                    setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR));
                    break;
                case SUL:
                    setCursor(new Cursor(Cursor.S_RESIZE_CURSOR));
                    break;
                case SUDOESTE:
                    setCursor(new Cursor(Cursor.SW_RESIZE_CURSOR));
                    break;
                case OESTE:
                    setCursor(new Cursor(Cursor.W_RESIZE_CURSOR));
                    break;
                case NOROESTE:
                    setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR));
                    break;
            }
        }else{
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    }
    
    /**
     * Evento chamado quando a janela é redimensionada.
     * @param e O evento do Oris.
     */
    private void windowResized(OrisEvent e) {
        if(resizeThread == null){
            resizeThread = new ResizeThread(this);
        }
        
        if(!resizeThread.isResizing()){
            resizeThread.startResizing();
        }
        
        int width = getSize().width;
        int height = getSize().height;
        int locationX = getLocation().x;
        int locationY = getLocation().y;
        
        switch(direcao){
            case NORTE:
                height -= e.getChangeY();
                locationY += e.getChangeY();
                break;
            case NORDESTE:
                height -= e.getChangeY();
                locationY += e.getChangeY();
                
                width = e.getPosX();
                break;
            case LESTE:
                width = e.getPosX();
                break;
            case SUDESTE:
                height = e.getPosY();
                
                width = e.getPosX();
                break;
            case SUL:
                height = e.getPosY();
                break;
            case SUDOESTE:
                height = e.getPosY();
                
                width -= e.getChangeX();
                locationX += e.getChangeX();
                break;
            case OESTE:
                width -= e.getChangeX();
                locationX += e.getChangeX();
                break;
            case NOROESTE:
                height -= e.getChangeY();
                locationY += e.getChangeY();

                width -= e.getChangeX();
                locationX += e.getChangeX();
                break;
        }
        
        resizeThread.update(width, height, locationX, locationY);
    }
    
    /**
     * Evento chamado quando a janela é deslocada de posição.
     * @param e O evento do Oris.
     */
    public void windowMoved(OrisEvent e) {
        if(moveThread == null){
            moveThread = new MoveThread(this);
        }
        
        if(!moveThread.isMoving()){
            moveThread.startMove();
        }
        
        int locationX = getLocation().x + e.getChangeX();
        int locationY = getLocation().y + e.getChangeY();
        
        moveThread.update(locationX, locationY);
    }
    
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Variáveis Globais">
    
    private Component[] _componentes;
    
    int ultimaPosicaoX;
    int ultimaPosicaoY;
    boolean emArrastao;
    boolean estaMovendo;
    boolean estaRedimensionando;
    ResizeThread resizeThread;
    MoveThread moveThread;
    EnumDirecoes direcao;
    OrisBorder borda = new OrisBorder(new Insets(3, 3, 3, 3));
    
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Override">

    public void mouseDragged(MouseEvent evt) {
        int changeX = evt.getX() - ultimaPosicaoX;
        int changeY = evt.getY() - ultimaPosicaoY;
        int posX = evt.getX();
        int posY = evt.getY();
        
        if(!emArrastao){
            emArrastao = true;
            estaRedimensionando = borda.isOnBorder(getSize(), evt.getX(), evt.getY());
        }
        
        //Redimensionará a tela apenas se estiver o mouse na borda
        if(estaRedimensionando){
            OrisEvent event = new OrisEvent(changeX, changeY, direcao, true, 
                    posX, posY, this);
            
            estaRedimensionando = true;
            windowResized(event);
        }
        //Moverá a tela apenas se estiver o mouse na barra de título
        else {
            OrisEvent event = new OrisEvent(changeX, changeY, direcao, true,
                    posX, posY, this);

            estaRedimensionando = false;
            windowMoved(event);
        }
    }

    public void mouseMoved(MouseEvent evt) {
        ultimaPosicaoX = evt.getX();
        ultimaPosicaoY = evt.getY();
        
        emArrastao = false;
        estaRedimensionando = false;
        estaMovendo = false;
        
        if(resizeThread != null){
            resizeThread.stopResizing();
        }
        if(moveThread != null){
            moveThread.stopMoving();
        }
        
        organizaDirecoes(evt);
    }

    // </editor-fold>
}